import cv2
import os, json
import face_recognition
import numpy as np
import shutil
from  PIL import Image, ImageDraw, ImageFont


#新建文件夹来存储文件
def make_file(path):
    if os.path.exists(path):
        pass
    else:
        os.makedirs(path)


def RemoveDir(filepath):
    '''
    如果文件夹不存在就创建，如果文件存在就清空！

    '''
    if not os.path.exists(filepath):
        os.mkdir(filepath)
    else:
        shutil.rmtree(filepath)
        os.mkdir(filepath)



#获取人物的信息
def get_message():
    #打开摄像头
    cap = cv2.VideoCapture(0)
    #获得名字
    name = str(input("请输入你的英文名字："))
    #创建图片存储路劲
    new_path = 'image_data/' + name + '.jpg'
    #启动LBP模型 识别人脸
    face_cascade = cv2.CascadeClassifier("./static/haarcascade/haarcascade_frontalface_default.xml")#打开LBP模型文件  需要提前下载文件 路径自行改动

    while True:
        ret, image = cap.read() # 读取摄像头内容
        # 改变摄像头图像的大小，图像小，所做的计算就少
        small_frame = cv2.resize(image, (0, 0), fx=0.25, fy=0.25)


        if ret:#如果成功捕获图像
            cv2.putText(small_frame, '请正视屏幕', (10, 20), cv2.FONT_HERSHEY_COMPLEX, 1.0, (255, 255, 255), 1)
            gray = cv2.cvtColor(small_frame, cv2.COLOR_RGB2GRAY)  # 转化为灰度图
            faces = face_cascade.detectMultiScale(gray, 1.3, 5)
            for (x, y, w, h) in faces:
                cv2.rectangle(small_frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
            # 捕获人脸，后写入文件跳出捕获
            if (len(faces) != 0):
                cv2.imwrite(new_path, gray)
                break
            cv2.imshow('test2', small_frame)
        if cv2.waitKey(1) & 0xff == ord('q'):
            break
    #关闭所有摄像头窗口
    cap.release()
    cv2.destroyAllWindows()
    return new_path, name


def get_image_encond(image_path, image_name):
    image = face_recognition.load_image_file(image_path)
    enconding_name = str(image_name) + '_face_encoding'
    res = face_recognition.face_encodings(image)
    enconding_name = face_recognition.face_encodings(image)[0]

    return enconding_name



#定义显示中文的函数  注意调用本文开头的那三个库
def  change_cv2_draw(image, strs, local, size, color):
    ''' 在图片上显示汉字 输入为 图片，汉字字符，左上角坐标， 字体大小， 字体颜色
    返回处理后的图片'''

    cv2img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    pilimg = Image.fromarray(cv2img)
    draw = ImageDraw.Draw(pilimg)
    font = ImageFont.truetype("/System/Library/Fonts/NewYork.ttf", size, encoding="utf-8")
    draw.text(local, strs, color, font=font)
    # draw.text(local, strs, color )
    image = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR)

    return image





def verification_face( ):

    #¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥     先检测 这个登陆图片是否符合要求
    username = 'admin'
    login_filename = 'lijiajia.png'
    login_path = os.path.join('static/face_data_login', login_filename)

    # 将图片进行编码转化
    # obama_image = face_recognition.load_image_file('%s' % (login_path) )  # 载入图片
    obama_image = cv2.imread( login_path )  # 读取图片
    # 把图片变成原来的 1/4  大小  减少计算量  加快运行速率
    obama_image = cv2.resize(obama_image, (0, 0), fx=0.5, fy=0.5)
    face_recognition_res = face_recognition.face_encodings(obama_image)
    if not face_recognition_res:
        print('未识别到人脸面部信息！！！')
        return False, '未识别到人脸面部信息！！！'
    obama_face_enconding = face_recognition_res[0]  # 将图片进行编码


    # 存入特征值
    know_face_encondings = [
        obama_face_enconding,
    ]

    # 匹配姓名
    know_face_names = [
        username,
    ]

    #读取之前注册的数据图片
    # new_name = 'lijiajia'
    # register_path = 'static/face_data_register/admin' ###############暂时写死
    # # 注册时文件名称
    # name = '20220419171458.png'
    #
    # #  注册的图片获取特征值
    # new_image_path = os.path.join( register_path, name)
    # new_encon = (get_image_encond(new_image_path, name)) # 获取图片编码
    #
    # know_face_encondings.append(new_encon) # 存入特征值
    # know_face_names.append(new_name) # 存入 特征名称

    print('know_face_encondings:::::::::: ', know_face_encondings)
    print('know_face_names:::::::::: ', know_face_names)



    # 读取注册图片

    frame = cv2.imread('static/face_data_register/admin/20220419171458.png')  # 读取图片
    # 把图片变成原来的 1/4  大小  减少计算量  加快运行速率
    small_frame = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
    rgb_samll_frame = small_frame[:, :, ::-1]

    # 在视频中找出所有的人脸 并将它们编码
    face_locations = face_recognition.face_locations(rgb_samll_frame)
    face_encondings = face_recognition.face_encodings(rgb_samll_frame, face_locations)







    face_names = []

    for face_enconding in face_encondings:

        # 跟已有的数据库进行查询
        matches = face_recognition.compare_faces(know_face_encondings, face_enconding, tolerance=0.5)
        name = 'unKnown'

        if True in matches:
            first_match_index = matches.index(True)
            name = know_face_names[first_match_index]

        face_names.append(name)
    print( 'face_nameS: ', face_names)


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)



# verification_face( )

# import os
#
# res = os.listdir('static/face_data_register')
# print(res)

# print(  os.listdir(  'abc'))